<template>
	<view class="content">
		<scroll-view class="msgview" show-scrollbar scroll-y :scroll-top="scrollTop">
			<view id="scroll-view-content">
				<view class="buttonview">
					<button style="width: 50%;" @click="GetMsgHistory()">加载历史</button>
					<button style="width: 50%;" @click="godwn()">返回底部</button>
				</view>
				<view class="onemsg" v-for="(item,index) in msgList">
					<image mode="aspectFit" style="width: 100rpx; height: 100rpx;margin-right: 5rpx;"
						:src="HttpTool.getUrl()+item.userimg"></image>
					<view style="max-width: 620rpx;">
						<view style="height: 1em;width: 1em;white-space:nowrap;">
							<view style="font-size: 0.8em;float: left;">
								{{item.username}}#{{item.userid}}时间：{{timestampToTime(item.time)}}
							</view>
						</view>
						<view style="background-color:white; border-radius: 10rpx;padding: 10rpx;">
							<view v-if="item.type === 'text'">{{item.text}}</view>
							<image v-if="item.type === 'img'" @click="clickImg(HttpTool.getUrl()+item.text)"
								mode="aspectFit" style="height: 400rpx;width: 600rpx;"
								:src="HttpTool.getUrl()+item.text">
							</image>
							<image v-if="item.type === 'smallimg'" mode="aspectFit"
								style="width: 200rpx;height: 200rpx;" :src="HttpTool.getUrl()+item.text"></image>
							<MyVideo v-if="item.type === 'video'" :videoUrl="HttpTool.getUrl()+item.text"></MyVideo>
							<uni-card @click="clickImgList(item.text)" v-if="item.type === 'imglist'">
								<image mode="aspectFit" slot='cover' style="width: 450rpx;height: 300rpx;"
									:src="HttpTool.getUrl()+item.text[0]"></image>
								<text class="uni-body">图集</text>
							</uni-card>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<view class="inputview">
			<view class="buttonview">
				<button style="width: 20%;" @click="clickSendImg()">图片</button>
				<button style="width: 20%;" @click="clickSendVideo()">视频</button>
				<button style="width: 20%;" @click="clickSendImgList()">图集</button>
				<button style="width: 20%;" @click="clickSendSmallImg()">表情</button>
				<button style="width: 20%;" @click="clickSend()">发送</button>
			</view>
			<uni-easyinput type="textarea" v-model="text" placeholder="请输入内容"></uni-easyinput>
		</view>
	</view>
</template>

<script>
	import MyVideo from "/pages/index/MyVideo.vue"
	export default {
		components: {
			MyVideo
		},
		data() {
			return {
				title: 'pkserver',
				msg: {
					text: '',
					type: '',
					userid: ''
				},
				text: '',
				msgList: [],
				imgsrc: '',
				videosrc: '',
				imgsrcList: [],
				scrollTop: 0,
				scrollViewHeight: 0,
				isgodown: true
			}
		},
		onLoad() {
			this.msg.userid = this.Device.deviceId
			this.WebSocketTool.imUpdate = this.newMsgRecall
			this.newMsgRecall()
		},
		methods: {
			godwn() {
				this.isgodown = true
				this.$nextTick(() => {
					uni.createSelectorQuery().in(this).select('#scroll-view-content').boundingClientRect((res) => {
						let top = res.height - this.scrollViewHeight;
						console.log(top);
						if (top > 0) {
							this.scrollTop = top+1;
						}
					}).exec()
				})
			},
			async GetMsgHistory() {
				this.isgodown = false
				let time = '0'
				if (this.msgList.length > 0) {
					time = this.msgList[0].time
				}
				let res = await this.HttpTool.GetMsgHistory(this, time)
				if (res.code !== 200) {
					uni.showToast({
						title: res.message,
						duration: 2000,
						icon: "error"
					})
					return
				}
				if(res.data.length === 0){
					uni.showToast({
						icon: 'error',
						title: '没啦',
						duration: 2000,
					});
				}
				for (var i = 0; i < res.data.length; i++) {
					if (res.data[i].type === 'imglist') {
						res.data[i].text = JSON.parse(res.data[i].text)
					}
					this.msgList.unshift(res.data[i])
				}
			},
			clickImgList(urls) {
				for (var i = 0; i < urls.length; i++) {
					urls[i] = this.HttpTool.getUrl() + urls[i]
				}
				uni.previewImage({
					urls: urls,
					longPressActions: {
						itemList: ['保存图片'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
							uni.downloadFile({
								url: urls[data.index], //仅为示例，并非真实的资源
								success: (res) => {
									if (res.statusCode === 200) {
										console.log('下载成功');
										uni.showToast({
											title: '下载成功',
											duration: 2000,
										})
									}
									console.log(res.tempFilePath);
									let tempFilePath = res.tempFilePath
									uni.saveImageToPhotosAlbum({
												filePath: tempFilePath,
												success: function () {
													console.log('save success');
												}
											})
								},
								complete: ()=> {uni.hideLoading();}
							})
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				})
			},
			clickImg(url) {
				// 预览图片
				uni.previewImage({
					urls: [url],
					longPressActions: {
						itemList: ['保存图片'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
							uni.showLoading({
								title: '下载中',
								mask: true
							});
							uni.downloadFile({
								url: url, //仅为示例，并非真实的资源
								success: (res) => {
									if (res.statusCode === 200) {
										console.log('下载成功');
										uni.showToast({
											title: '下载成功',
											duration: 2000,
										})
									}
									console.log(res.tempFilePath);
									let tempFilePath = res.tempFilePath
									uni.saveImageToPhotosAlbum({
												filePath: tempFilePath,
												success: function () {
													console.log('save success');
												}
											})
								},
								complete: ()=> {uni.hideLoading();}
							});
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				})
			},
			async clickSendImg() {
				let that = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						that.imgsrc = res.tempFilePaths[0]
						console.log(that.imgsrc);
						that.SendImg()
					}
				});
			},
			async clickSendImgList() {
				let that = this
				uni.chooseImage({
					count: 100, //默认9
					sizeType: ['original'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						that.imgsrcList = res.tempFilePaths
						that.SendImgList()
					}
				});
			},
			async clickSendSmallImg() {
				let that = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						that.imgsrc = res.tempFilePaths[0]
						that.SendSmallImg()
					}
				});
			},
			async clickSendVideo() {
				let that = this
				uni.chooseVideo({
					success: function(res) {
						that.videosrc = res.tempFilePath
						console.log(that.videosrc);
						that.SendVideo()
					}
				});
			},
			async upload(path) {
				uni.showLoading({
					title: '上传中',
					mask: true
				});
				let res = await this.HttpTool.UpImFile(this, path)
				uni.hideLoading();
				res = JSON.parse(res)
				if (res.code !== 200) {
					uni.showToast({
						icon: 'error',
						title: '上传失败',
						duration: 2000,
					});
					return
				} else {
					uni.showToast({
						title: '上传成功',
						duration: 2000,
					});
				}
				return res.data
			},
			async SendImgList() {
				let paths = []
				for (var i = 0; i < this.imgsrcList.length; i++) {
					let filepath = this.imgsrcList[i]
					uni.showLoading({
						title: '上传中',
						mask: true
					});
					let resUp = await this.HttpTool.UpImFile(this, filepath)
					uni.hideLoading();
					resUp = JSON.parse(resUp)
					if (resUp.code !== 200) {
						uni.showToast({
							icon: 'error',
							title: '上传失败',
							duration: 2000,
						});
						return
					} else {
						uni.showToast({
							title: '上传成功',
							duration: 2000,
						});
					}
					//const path = await this.upload(this,filepath)
					paths.push(resUp.data)
				}
				let text = JSON.stringify(paths)
				this.msg.type = 'imglist'
				this.msg.text = text
				let res = await this.HttpTool.SendMsg(this, this.msg)
				if (res.code !== 200) {
					uni.showToast({
						title: res.message,
						duration: 2000,
						icon: "error"
					})
					return
				}
				this.imgsrcList = []
			},
			async SendImg() {
				let path = await this.upload(this.imgsrc)
				this.msg.type = 'img'
				if (path === undefined || path === null || path === '') {
					return
				}
				this.msg.text = path
				let res = await this.HttpTool.SendMsg(this, this.msg)
				if (res.code !== 200) {
					uni.showToast({
						title: res.message,
						duration: 2000,
						icon: "error"
					})
					return
				}
				this.imgsrc = ''
			},
			async SendSmallImg() {
				let path = await this.upload(this.imgsrc)
				this.msg.type = 'smallimg'
				if (path === undefined || path === null || path === '') {
					return
				}
				this.msg.text = path
				let res = await this.HttpTool.SendMsg(this, this.msg)
				if (res.code !== 200) {
					uni.showToast({
						title: res.message,
						duration: 2000,
						icon: "error"
					})
					return
				}
				this.imgsrc = ''
			},
			async SendVideo() {
				let path = await this.upload(this.videosrc)
				this.msg.type = 'video'
				if (path === undefined || path === null || path === '') {
					return
				}
				this.msg.text = path
				let res = await this.HttpTool.SendMsg(this, this.msg)
				if (res.code !== 200) {
					uni.showToast({
						title: res.message,
						duration: 2000,
						icon: "error"
					})
					return
				}
				this.videosrc = ''
			},
			async clickSend() {
				this.msg.type = 'text'
				if (this.text === undefined || this.text === null || this.text === '') {
					return
				}
				this.msg.text = this.text
				let res = await this.HttpTool.SendMsg(this, this.msg)
				if (res.code !== 200) {
					uni.showToast({
						title: res.message,
						duration: 2000,
						icon: "error"
					})
					return
				}
				this.text = ''
			},
			async newMsgRecall() {
				let time = '0'
				if (this.msgList.length > 0) {
					time = this.msgList[this.msgList.length - 1].time
				}
				let res = await this.HttpTool.GetMsg(this, time)
				if (res.code !== 200) {
					uni.showToast({
						title: res.message,
						duration: 2000,
						icon: "error"
					})
					return
				}
				for (var i = 0; i < res.data.length; i++) {
					if (res.data[i].type === 'imglist') {
						res.data[i].text = JSON.parse(res.data[i].text)
					}
					this.msgList.push(res.data[i])
				}
				if (res.data.length > 0 && this.isgodown) {
					console.log("滚");
					this.$nextTick(() => {
						uni.createSelectorQuery().in(this).select('#scroll-view-content').boundingClientRect((
							res) => {
							let top = res.height - this.scrollViewHeight;
							if (top > 0) {
								this.scrollTop = top;
							}
						}).exec()
					})
				}
			},
			timestampToTime(timestamp) {
				timestamp = Number(timestamp)
				// 时间戳为10位需*1000，时间戳为13位不需乘1000
				var date = new Date(timestamp);
				var Y = date.getFullYear() + "-";
				var M =
					(date.getMonth() + 1 < 10 ?
						"0" + (date.getMonth() + 1) :
						date.getMonth() + 1) + "-";
				var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
				var h = date.getHours() + ":";
				var m = date.getMinutes() + ":";
				var s = date.getSeconds();
				return Y + M + D + h + m + s;
			}
		}
	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		height: 100%;
	}

	.buttonview {
		display: flex;
		flex-direction: row;
	}

	.inputview {}

	.msgview {
		overflow: scroll;
		flex: 1;
		background-color: oldlace;
	}

	page {
		height: 100%;
	}

	.onemsg {
		display: flex;
		margin-bottom: 10rpx;
	}
</style>
